package com.ctvit.sjk.knowledge.paragraph.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctvit.sjk.knowledge.paragraph.mapper.TabParagraphMapper;
import com.ctvit.sjk.knowledge.paragraph.pojo.domain.TabParagraph;
import com.ctvit.sjk.knowledge.paragraph.pojo.vo.ParagraphGetVO;
import com.ctvit.sjk.knowledge.paragraph.service.ITabParagraphService;
import com.ctvit.sjk.knowledge.problem.pojo.domain.TabProblemParagraphMapping;
import com.ctvit.sjk.knowledge.problem.service.ITabProblemParagraphMappingService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分段Service业务层处理
 *
 * @author heyingcheng
 * @date 2025/3/22
 */
@Service
public class TabParagraphServiceImpl extends ServiceImpl<TabParagraphMapper, TabParagraph> implements ITabParagraphService {

    private final ITabProblemParagraphMappingService tabProblemParagraphMappingService;

    public TabParagraphServiceImpl(ITabProblemParagraphMappingService tabProblemParagraphMappingService) {
        this.tabProblemParagraphMappingService = tabProblemParagraphMappingService;
    }

    @Override
    public List<ParagraphGetVO> listProgramParagraph(String datasetId, String problemId) {
        LambdaQueryWrapper<TabProblemParagraphMapping> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TabProblemParagraphMapping::getDatasetId, datasetId);
        wrapper.eq(TabProblemParagraphMapping::getProblemId, problemId);

        List<String> paragraphIdList = tabProblemParagraphMappingService.list(wrapper).stream().map(TabProblemParagraphMapping::getParagraphId).collect(Collectors.toList());
        if (paragraphIdList.isEmpty()) {
            return Collections.emptyList();
        }

        return listByIds(paragraphIdList).stream().map(ParagraphGetVO::new).collect(Collectors.toList());
    }

    @Override
    public List<ParagraphGetVO> listDocumentParagraph(String datasetId, String documentId, String title, String content) {
        LambdaQueryWrapper<TabParagraph> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(title), TabParagraph::getParagraphTitle, title);
        wrapper.like(StringUtils.isNotBlank(content), TabParagraph::getParagraphContent, content);
        wrapper.eq(TabParagraph::getDatasetId, datasetId);
        wrapper.eq(TabParagraph::getDocumentId, documentId);
        wrapper.orderByDesc(TabParagraph::getUpdateTime);

        return list(wrapper).stream().map(ParagraphGetVO::new).collect(Collectors.toList());
    }

}
